<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="标记物类型" prop="markerType">
        <el-select v-model="queryParams.markerType" placeholder="请选择标记物类型" clearable>
          <el-option v-for="dict in markerTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="标记物名称" prop="markerName">
        <el-input v-model="queryParams.markerName" placeholder="请输入标记物名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['management:marker:add']">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" icon="el-icon-edit" :disabled="single" @click="handleUpdate" v-hasPermi="['management:marker:edit']">修改</el-button></el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['management:marker:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="markerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="类型" align="center" prop="markerType" width="55" :formatter="markerTypeFormat" />
      <el-table-column label="名称" align="center" prop="markerName" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="画图形状" align="center" prop="shapeType" :formatter="shapeTypeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['management:marker:edit']">修改</el-button>
          <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['management:marker:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改标记物管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" @close="closeDialog" append-to-body>
      <el-steps :active="1" simple>
        <el-step title="填写信息" icon="el-icon-edit"></el-step>
        <el-step title="绘制地图" icon="el-icon-location"></el-step>
        <el-step title="保存内容" icon="el-icon-check"></el-step>
      </el-steps>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" style="margin-top: 10px;">
          <el-tab-pane label="基础信息" name="first">
            <el-form-item label="标记物名称" prop="markerName"><el-input v-model="form.markerName" placeholder="请输入标记物名称" /></el-form-item>
            <el-form-item label="标记物地址" prop="address"><el-input v-model="form.address" placeholder="请输入标记物地址" /></el-form-item>
            <el-form-item label="标记物类型" prop="markerType">
              <el-select v-model="form.markerType" placeholder="请选择标记物类型" @change="markerTypeChange">
                <el-option v-for="dict in markerTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属景区">
              <el-checkbox-group v-model="contentIdsList">
                <el-checkbox v-for="(item, index) in contentList" :key="'jq' + index" :label="item.contentId">{{ item.title }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="地图" name="second">
            <el-row>
              <el-col :span="12">
                <el-form-item label="坐标lat" prop="lat"><el-input disabled v-model="form.lat" placeholder="请输入坐标lat" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="坐标lng" prop="lng"><el-input disabled v-model="form.lng" placeholder="请输入坐标lng" /></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="画图形状">
                  <el-radio-group v-model="form.shapeType" @change="shapeChange">
                    <el-radio v-for="dict in shapeTypeOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="圆形的半径" prop="radius" v-if="form.shapeType == 'circle'"><el-input v-model="form.radius" placeholder="请输入圆形的半径" /></el-form-item>
                <el-form-item label="icon图片" v-if="form.shapeType == 'marker'"><imageUpload v-model="form.iconPictures" :limit="1" :file-size="2" /></el-form-item>
              </el-col>
            </el-row>
            <div id="container" ref="containerRef" style="height: 500px"></div>
          </el-tab-pane>
          <el-tab-pane label="简介详情" name="third">
            <el-form-item label="简介"><editor v-model="form.briefContent" :min-height="192" /></el-form-item>
            <el-form-item label="详情"><editor v-model="form.content" :min-height="192" /></el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMarker, getMarker, delMarker, addMarker, updateMarker, exportMarker } from '@/api/management/marker';
import { selectLabel } from '@/api/management/label';
export default {
  name: 'Marker',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标记物管理表格数据
      markerList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 画图形状字典
      shapeTypeOptions: [],
      // 标记物类型字典
      markerTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        markerName: null,
        orderByColumn: 'markerId', //排序字段
        isAsc: 'desc' //排序方式
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        markerName: [{ required: true, message: '请输入标记物名称' }],
        markerType: [{ required: true, message: '请选择标记物类型' }]
      },
      activeName: 'first',
      centerLat: 29.4270023,
      centerLng: 88.26060954,
      tmap: undefined,
      map: undefined,
      baseUrl: process.env.VUE_APP_BASE_API,
      labelList: undefined,
      contentList: [],
      contentIdsList: [],
      positionList: []
    };
  },
  created() {
    this.getList();
    this.getDicts('shape_type').then(response => {
      this.shapeTypeOptions = response.data;
    });
    this.getDicts('marker_type').then(response => {
      this.markerTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询标记物管理列表 */
    getList() {
      this.loading = true;
      listMarker(this.queryParams).then(response => {
        this.markerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 标记物类型字典翻译
    markerTypeFormat(row, column) {
      return this.selectDictLabel(this.markerTypeOptions, row.markerType);
    },
    // 画图形状字典翻译
    shapeTypeFormat(row, column) {
      return this.selectDictLabel(this.shapeTypeOptions, row.shapeType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      if (this.map) {
        this.map.destroy();
        this.map = null;
      }
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        markerId: null,
        markerType: null,
        markerName: null,
        address: null,
        showPictures: null,
        iconPictures: null,
        lat: null,
        lng: null,
        labelText: null,
        businessHours: null,
        shapeType: null,
        locationSet: null,
        radius: null,
        briefContent: null,
        content: null
      };
      this.form.shapeType = 'marker';
      (this.activeName = 'first'), this.shapeChange();
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.markerId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加标记物管理';
      this.contentIdsList = [];
      this.contentList = [];
      getMarker(0).then(response => {
        this.contentList = response.data.contentList;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const markerId = row.markerId || this.ids;
      getMarker(markerId).then(response => {
        this.form = response.data.info;
        this.open = true;
        this.title = '修改标记物管理';
        if (response.data.info.labelText) {
          this.form.labelText = response.data.info.labelText.split(',');
        }

        this.contentList = response.data.contentList;
        this.contentIdsList = response.data.contentIdsList;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.labelText) {
            this.form.labelText = this.form.labelText.join(',');
          }
          this.form.contentIdsList = this.contentIdsList;
/*          if (this.form.contentIdsList.length == 0) {
            this.msgError('请关联所属景区');
            return;
          }
          if (!this.form.locationSet) {
            this.msgError('请在地图上绘制路线或者建筑物');
            this.activeName = 'second';
            this.handleClick();
            return;
          } */
          if (this.form.markerId != null) {
            updateMarker(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.open = false;
              if (this.map) {
                this.map.destroy();
                this.map = null;
              }
              this.getList();
            });
          } else {
            addMarker(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.open = false;
              if (this.map) {
                this.map.destroy();
                this.map = null;
              }
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const markerIds = row.markerId || this.ids;
      this.$confirm('是否确认删除标记物管理编号为"' + markerIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delMarker(markerIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有标记物管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          return exportMarker(queryParams);
        })
        .then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /**初始化地图 */
    initMap() {
      this.positionList = [];
      this.TMap().then(_tmap => {
        this.tmap = _tmap;
        console.log(this.$refs.containerRef);
        // 初始化地图
        var center = new _tmap.LatLng(this.centerLat, this.centerLng); // 设置地图中心点坐标
        if (this.form.lat && this.form.lng) {
          center = new _tmap.LatLng(this.form.lat, this.form.lng);
        }

        this.map = new _tmap.Map(this.$refs.containerRef, {
          zoom: 15, // 设置地图缩放级别
          center: center
        });

        this.marker = new _tmap.MultiMarker({
          map: this.map
        });
        this.polyline = new _tmap.MultiPolyline({
          map: this.map
        });
        this.polygon = new _tmap.MultiPolygon({
          map: this.map
        });
        this.circle = new _tmap.MultiCircle({
          map: this.map
        });

        if (this.form.shapeType == 'marker' && this.form.lat && this.form.lng) {
          // 点标签

          //添加自定图标
          if (this.form.iconPictures) {
            var style = new _tmap.MarkerStyle({
              width: 40,
              height: 40,
              anchor: { x: 16, y: 32 },
              src: this.baseUrl + this.form.iconPictures
            });

            this.marker.setStyles({ default: style });
          }

          //   var centerMarker = new _tmap.LatLng(this.form.lat, this.form.lng)
          //   console.log(center)
          //   var geometrie = {
          //     position: centerMarker
          //   }
          var locationSet = JSON.parse(this.form.locationSet);
          var geometries = [];
          locationSet.forEach((item, index) => {
            this.positionList.push(item);
            var position = {
              position: new TMap.LatLng(item.lat, item.lng)
            };
            geometries.push(position);
          });
          console.log(geometries);
          this.marker.setGeometries(geometries);
        } else if (this.form.shapeType == 'polyline' && this.form.lat && this.form.lng) {
          //线
          //  var centerPolyline = new _tmap.LatLng(this.form.lat, this.form.lng)
          var locationSet = JSON.parse(this.form.locationSet);

          var geometries = [];

          locationSet.forEach(item => {
            geometries.push(new _tmap.LatLng(item.lat, item.lng));
          });
          this.polyline.setGeometries([
            {
              paths: geometries
            }
          ]);
        } else if (this.form.shapeType == 'polygon' && this.form.lat && this.form.lng) {
          //线
          //  var centerPolyline = new _tmap.LatLng(this.form.lat, this.form.lng)
          var locationSet = JSON.parse(this.form.locationSet);

          var geometries = [];

          locationSet.forEach(item => {
            geometries.push(new _tmap.LatLng(item.lat, item.lng));
          });
          this.polygon.setGeometries([
            {
              paths: geometries
            }
          ]);
        } else if (this.form.shapeType == 'circle' && this.form.lat && this.form.lng) {
          //线
          //  var centerPolyline = new _tmap.LatLng(this.form.lat, this.form.lng)
          var geometry = { center: new _tmap.LatLng(this.form.lat, this.form.lng), radius: this.form.radius };
          console.log(geometry);
          this.circle.setGeometries([geometry]);
        }

        // 初始化几何图形及编辑器
        this.editor = new _tmap.tools.GeometryEditor({
          map: this.map, // 编辑器绑定的地图对象
          overlayList: [
            // 可编辑图层
            {
              overlay: this.marker,
              id: 'marker'
            },
            {
              overlay: this.polyline,
              id: 'polyline'
            },
            {
              overlay: this.polygon,
              id: 'polygon'
            },
            ,
            {
              overlay: this.circle,
              id: 'circle'
            }
          ],
          actionMode: _tmap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
          activeOverlayId: this.form.shapeType, // 激活图层
          selectable: true, // 开启点选功能
          snappable: true // 开启吸附
        });
        // 监听绘制结束事件，获取绘制几何图形
        this.editor.on('draw_complete', geometry => {
          console.log(geometry);
          var position = undefined;
          var geometries = [geometry];

          if (this.form.shapeType === 'marker') {
            position = geometry.position;
            this.positionList.push(position);
            this.form.locationSet = JSON.stringify(this.positionList);
            console.log(this.form.locationSet);
            //this.marker.setGeometries(geometries)
          } else if (this.form.shapeType === 'polyline') {
            position = geometry.paths[0];
            this.form.locationSet = JSON.stringify(geometry.paths);
            this.polyline.setGeometries(geometries);
          } else if (this.form.shapeType === 'polygon') {
            position = geometry.paths[0];
            this.form.locationSet = JSON.stringify(geometry.paths);
            this.polygon.setGeometries(geometries);
          } else if (this.form.shapeType === 'circle') {
            position = geometry.center;
            this.form.radius = geometry.radius.toFixed(2);
            this.form.locationSet = JSON.stringify(geometry.center);
            this.circle.setGeometries(geometries);
          }
          if (position) {
            this.form.lat = position.lat;
            this.form.lng = position.lng;
          }
        });
        // this.editor.disable()
      });
    },
    handleClick() {
      if ((this.activeName = 'second')) {
        if (!this.map) {
          setTimeout(() => {
            this.initMap();
          }, 500);
        }
      }
    },
    shapeChange() {
      this.form.radius = 0;
      this.form.locationSet = '';
      if (this.map && this.editor) {
        this.marker.setGeometries([]);
        this.polyline.setGeometries([]);
        this.polygon.setGeometries([]);
        this.circle.setGeometries([]);

        this.editor.setActiveOverlay(this.form.shapeType);
      }
    },
    markerTypeChange(val) {
      selectLabel(val).then(res => {
        console.log(res);
        this.labelList = res.data;
      });
      // selectLabel(this.form.markerType).then(res=>{
      //     console.log(res);
      // })
    },
    closeDialog() {
      this.open = false;
      if (this.map) {
        this.map.destroy();
        this.map = null;
      }
      this.getList();
    }
  }
};
</script>
<style scoped>
html,
body {
  height: 100%;
  margin: 0px;
  padding: 0px;
}
#container {
  width: 100%;
  height: 550px;
}

#toolControl {
  position: absolute;
  top: 10px;
  left: 0px;
  right: 0px;
  margin: auto;
  width: 168px;
  z-index: 1001;
}
.toolItem {
  width: 40px;
  height: 40px;
  float: left;
  margin: 1px;
  padding: 4px;
  border-radius: 3px;
  background-size: 30px 30px;
  background-position: 4px 4px;
  background-repeat: no-repeat;
  box-shadow: 0 1px 2px 0 #e4e7ef;
  background-color: #ffffff;
  border: 1px solid #ffffff;
}
.toolItem:hover {
  border-color: #789cff;
}
.active {
  border-color: #d5dff2;
  background-color: #d5dff2;
}

#polygon {
  background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png');
}
#circle {
  background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/circle.png');
}
</style>
